﻿// Copyright (c)  MOKEYISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace NSQL.Query.Extensions
{
    public static class TypeExtensions
    {
        public static bool IsIEnumerable(this Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
        }
        
        public static Type GetImplementedIEnumerableType(this Type type)
        {
            // Get IEnumerable implementation. Either type is IEnumerable<T> for some T, 
            // or it implements IEnumerable<T> for some T. We need to find the interface.
            if (type.IsIEnumerable()) return type;
            var t = type.FindInterfaces((m, o) => m.IsIEnumerable(), null);
            Debug.Assert(t.Length == 1);
            return t[0];
        }
    }
}